package com.wo.cloud.auth.config;

import cn.hutool.core.util.ObjectUtil;
import com.wo.cloud.auth.entity.SysUserDetails;
import com.wo.cloud.auth.service.UserService;
import com.wo.cloud.auth.service.impl.ClientDetailsServiceImpl;
import com.wo.cloud.auth.sms.SmsCodeAuthenticationProvider;
import com.wo.cloud.auth.sms.SmsCodeTokenGranter;
import com.wo.cloud.core.constant.ClientDetailsConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.security.KeyPair;
import java.util.*;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/3/5 15:53
 * Description: 配置token 存放在jwt， 配置第三方应用
 */

@Configuration
public class AuthorizationJWTConfig extends AuthorizationServerConfigurerAdapter {


    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private DataSource dataSource;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserService userService;


    /**
     * jwt的token转换器， 把用户的信息转成jwt的形式颁发出去
     *
     * @return
     */
    @Bean
    public JwtAccessTokenConverter getJwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        // 非对称加密
        ClassPathResource classPathResource = new ClassPathResource("cxs-jwt.jks");
        // 创建钥匙工厂
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "cxs123".toCharArray());

        // 通过别名获取私钥
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("cxs-jwt");

        converter.setKeyPair(keyPair);
        return converter;
    }

    /**
     * 让oauth的token 和 JWT存储进行关联
     */
    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(getJwtAccessTokenConverter());
    }


    /**
     * 配置第三方应用
     * 四种授权模式:
     * 1. code模式: authorization_code
     * 2. 静默授权:
     * 3. 密码模式: password
     * 4. 客户端授权
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        // 采用数据库方式查询数据
        ClientDetailsServiceImpl clientDetailsService = new ClientDetailsServiceImpl(dataSource);
        clientDetailsService.setSelectClientDetailsSql(ClientDetailsConstant.selectClientDetailsSql);
        clients.withClientDetails(clientDetailsService);

//        clients.inMemory()
//                .withClient("web")  // 第三方应用客户端名称
//                .secret(passwordEncoder.encode("web-secret")) // 第三方应用密码
//                .scopes("read") // 第三方应用作用域
//                .authorizedGrantTypes("authorization_code") // code码授权
//                .accessTokenValiditySeconds(7200) // token有效时间
//                .redirectUris("https://www.baidu.com") // 授权后跳转的uri地址
//                .and()
//                // 配置第二个客户端信息:
//                .withClient("qq")
//                .secret(passwordEncoder.encode("qq-secret"))
//                .scopes("write")
//                .authorizedGrantTypes("password")  // 密码授权
//                .accessTokenValiditySeconds(7200)
//                .redirectUris("https://www.baidu.com");

    }


    /**
     * 需要暴露授权服务给token存储
     * 暴露授权服务器给认证管理器
     *
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // token 增强链
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), getJwtAccessTokenConverter()));

        endpoints.accessTokenConverter(getJwtAccessTokenConverter())
                .authenticationManager(authenticationManager)
                .tokenEnhancer(tokenEnhancerChain)
                // 配置 token 存储方式
                .tokenStore(tokenStore())
                // 配置自定义 登录认证模式
                .tokenGranter(tokenGranter(endpoints));
    }


    /**
     * 配置 web 通过 form 表单提交登录请求
     *
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 允许表单认证请求(否则request body提交报错: 401:Unauthorized)
        security.tokenKeyAccess("permitAll()")
                // 允许 /oauth/token_check端点的访问
                .checkTokenAccess("permitAll()")
                .passwordEncoder(passwordEncoder)
                .allowFormAuthenticationForClients();
    }

    /**
     * jwt token增强，添加额外信息
     *
     * @return
     */
    @Bean
    public TokenEnhancer tokenEnhancer() {
        return new TokenEnhancer() {
            @Override
            public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
                // 添加登录返回的额外信息
                final Map<String, Object> additionMessage = new HashMap<>();

                // 获取当前登录用户的信息
                SysUserDetails sysUserDetails = (SysUserDetails) authentication.getUserAuthentication().getPrincipal();

                // 将用户部分信息 放入 jwt token中
                if (ObjectUtil.isNotNull(sysUserDetails)) {
                    // 获取用户所属租户 ID
                    additionMessage.put("user_id", sysUserDetails.getId());
                    additionMessage.put("tenant_id", sysUserDetails.getTenantId());
                }

                ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionMessage);
                return accessToken;
            }
        };
    }


    /**
     * 配置自定义 登录认证 模式
     * @param endpoints
     * @return
     */
    private TokenGranter tokenGranter(final AuthorizationServerEndpointsConfigurer endpoints){
        // 获取自带 认证模式: 四种
        List<TokenGranter> tokenGranters = new ArrayList<>(Collections.singletonList(endpoints.getTokenGranter()));

        // 添加自定义认证
        tokenGranters.add(new SmsCodeTokenGranter(authenticationManager, endpoints.getTokenServices(), endpoints.getClientDetailsService(),
                endpoints.getOAuth2RequestFactory(),redisTemplate));
        return new CompositeTokenGranter(tokenGranters);
    }


    @Bean
    public SmsCodeAuthenticationProvider provider() {
        return new SmsCodeAuthenticationProvider(userService);
    }

}
